<template>
  <div class="ebook container">
    <div id="read"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import Epub from 'epubjs'
global.ePub = Epub
export default {
  data() {
    return {
      rendition: null,
      book: null,
      timer: null,
      bigTimer: null,
      seconds: 0
    }
  },
  computed: {
    ...mapState({
      getCurrentPlayItem: state => state.course.currentPlayItem
    })
  },
  mounted() {
    this.$api.getCourseDetail(this.$route.params.id, res => {
      const { data } = res
      this.handleSectionFileurl(data.course_type === 4 ? data.id : 0)
    })
  },
  methods: {
    // 获取播放地址
    handleSectionFileurl(class_id) {
      this.$api.getCourseSectionFileurl(
        this.getCurrentPlayItem.course_id,
        this.getCurrentPlayItem.id,
        { class_id: class_id },
        res => {
          let data = res.data
          if (data.url_type == 2) {
            this.showEpub(data.fileurl_string)
            this.start()
            this.timing()
          }
        }
      )
    },
    showEpub(url) {
      this.book = Epub(url)
      this.rendition = this.book.renderTo('read', {
        width: 1217,
        manager: 'continuous',
        flow: 'scrolled'
      })
      this.rendition.display()
    },
    // 添加学习记录
    addLearning() {
      this.$api.createCourseRecord({
        course_id: this.getCurrentPlayItem.course_id,
        section_id: this.getCurrentPlayItem.id,
        current_time: this.seconds
      })
    },
    // 定时添加学习记录
    timing() {
      // 避免可能出现的倒计时重叠情况
      this.clearTimer(1)
      this.bigTimer = setInterval(() => {
        this.addLearning()
      }, 10000)
    },
    // 倒计时
    start() {
      // 避免可能出现的倒计时重叠情况
      this.clearTimer(2)
      this.timer = setInterval(() => {
        this.seconds++
      }, 1000)
    },
    // 停止倒计时
    async end() {
      await this.addLearning()
      this.clearTimer()
    },
    // 清除定时器
    clearTimer(type) {
      if (type === 1) {
        if (this.bigTimer) {
          clearInterval(this.bigTimer)
          this.bigTimer = null
        }
      } else if (type === 2) {
        if (this.timer) {
          clearInterval(this.timer)
          this.timer = null
        }
      } else {
        if (this.bigTimer || this.timer) {
          clearInterval(this.bigTimer)
          this.bigTimer = null
          clearInterval(this.timer)
          this.timer = null
        }
      }
    }
  },
  beforeDestroy() {
    this.end()
  }
}
</script>

<style lang="scss" scoped>
.ebook {
  margin-top: 10px;
  background-color: #fff;
  overflow: hidden;
  padding: 15px 0;
  #read {
    margin-right: -17px;
  }
}
</style>
